import { All, Controller, Query, Req } from "@nestjs/common";
import { apibefore } from "src/router";
import { createHash, createDecipheriv } from 'crypto'

@Controller(apibefore('/video'))
export class VideoController {
    constructor(){
    }
    sha1(str) {
        const md5sum = createHash('sha1');
        md5sum.update(str);
        const ciphertext = md5sum.digest('hex');
        return ciphertext;
    }
    _decode(data) {
        let aesKey = Buffer.from('ANaXPGf715ZV5iLzzd8nv4p42P8yfxAu2NVW8uWc8Xa' + '=', 'base64');
        let aesCipher = createDecipheriv("aes-256-cbc", aesKey, aesKey.slice(0, 16));
        aesCipher.setAutoPadding(false);
        let decipheredBuff = Buffer.concat([aesCipher.update(data, 'base64'), aesCipher.final()]);
        decipheredBuff = this.PKCS7Decoder(decipheredBuff);
        let len_netOrder_corpid = decipheredBuff.slice(16);
        let msg_len = len_netOrder_corpid.slice(0, 4).readUInt32BE(0);
        const result = len_netOrder_corpid.slice(4, msg_len + 4).toString();
        return result; // 返回一个解密后的明文-
    }
    PKCS7Decoder (buff) {
        var pad = buff[buff.length - 1];
        if (pad < 1 || pad > 32) {
            pad = 0;
        }
        return buff.slice(0, buff.length - pad);
    }

    @All('webhook')
    webhook(@Req() req, encrypt){
        const query = req.query;
        console.log('Request URL: ', req.url);
        const signature = query.msg_signature;
        const timestamp = query.timestamp;
        const nonce = query.nonce;
        let echostr;
        console.log('encrypt', encrypt);
        if (!encrypt) {
            echostr = query.echostr;
        } else {
            echostr = encrypt;
        }
        console.log('timestamp: ', timestamp);
        console.log('nonce: ', nonce);
        console.log('signature: ', signature);
        // 将 token/timestamp/nonce 三个参数进行字典序排序
        let token = 'WIdVyMOjGnswhSpuN6g3b3IrvmM'
        const tmpArr = [token, timestamp, nonce, echostr];
        const tmpStr = this.sha1(tmpArr.sort().join(''));
        console.log('Sha1 String: ', tmpStr);
        // 验证排序并加密后的字符串与 signature 是否相等
        if (tmpStr === signature) {
        // 原样返回echostr参数内容
        const result = this._decode(echostr);
        console.log('last', result);
        console.log('Check Success');
            return result;
        } else {
            console.log('Check Failed');
            return 'failed';
        }
    }
}